import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@views/Home'
import { isLogin } from '@utils'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: '主页',
    component: Home,
    meta: {
      needLogin: false
    }
  },
  {
    path: '/cates',
    name: '分类页',
    component: () => import('@views/Cates'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/phone',
    name: '联系我们',
    component: () => import('@views/Phone'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/carts',
    name: '购物车',
    component: () => import('@views/Carts'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/user',
    name: '个人中心',
    component: () => import('@views/User'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/listPages',
    name: '商品列表',
    component: () => import('@views/ListPages'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/details',
    name: '详情页',
    component: () => import('@views/Details'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/registry',
    name: '注册页',
    component: () => import('@views/Registry'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/login',
    name: '登录页',
    component: () => import('@views/Login'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/addLinkman',
    name: '添加联系人',
    component: () => import('@views/AddLinkman'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/editLinkman',
    name: '编辑联系人',
    component: () => import('@views/EditLinkman'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/showLinkman',
    name: '联系人列表',
    component: () => import('@views/ShowLinkman'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/confirmOrder',
    name: '确认订单',
    component: () => import('@views/ConfirmOrder'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/searchPage',
    name: '搜索页',
    component: () => import('@views/SearchPage'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/searchResults',
    name: '搜索列表',
    component: () => import('@views/SearchResults'),
    meta: {
      needLogin: false
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  // 判断当前路由是否需要登录
  if (to.meta.needLogin) {
    // 需要登录
    if (isLogin()) {
      // 有token直接放行
      next()
    } else {
      next({
        path: '/login',
        query: {
          from: to.path
        }
      })
    }
  } else {
    // 不需要登录
    next()
  }
})
export default router
